package com.dd.census.controller.common;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import com.dd.census.entity.SysUser;
import com.dd.census.tools.SysException;
import com.dd.census.tools.TokenHelper;

public class BaseController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 处理完成（200)
	 * 
	 * @param request 请求
	 * @return 处理结果
	 */
	protected ResponseEntity<Object> doSuccess(HttpServletRequest request) {
		return doSuccess(request, HttpStatus.OK);
	}

	/**
	 * 处理完成
	 * 
	 * @param request 请求
	 * @param httpStatus 状态码
	 * @return 处理结果
	 */
	protected ResponseEntity<Object> doSuccess(HttpServletRequest request, HttpStatus httpStatus) {
		return doSuccess(request, "", httpStatus);
	}

	/**
	 * 处理完成(200)
	 * 
	 * @param request 请求
	 * @param data 返回内容
	 * @return 处理结果
	 */
	protected ResponseEntity<Object> doSuccess(HttpServletRequest request, Object data) {
		return doSuccess(request, data, HttpStatus.OK);
	}

	/**
	 * 处理完成
	 * 
	 * @param request 请求
	 * @param data 返回值
	 * @param httpStatus 状态码
	 * @return 处理结果
	 */
	protected ResponseEntity<Object> doSuccess(HttpServletRequest request, Object data, HttpStatus httpStatus) {
		logger.info("Request Complete. Path:{} Status:{}", request.getRequestURI(), httpStatus);
		return new ResponseEntity<Object>(data, HttpStatus.OK);
	}

	/**
	 * 系统错误(500)
	 * 
	 * @param request 请求
	 * @return 处理结果
	 */
	protected ResponseEntity<Object> doFaild(HttpServletRequest request) {
		return doFaild(request, HttpStatus.INTERNAL_SERVER_ERROR);
	}

	/**
	 * 系统错误
	 * 
	 * @param request 请求
	 * @param httpStatus 状态吗
	 * @return 处理结果
	 */
	protected ResponseEntity<Object> doFaild(HttpServletRequest request, HttpStatus httpStatus) {
		return doFaild(request, new SysException(httpStatus));
	}
	
	/**
	 * 处理完成(400)
	 * 
	 * @param request 请求
	 * @param data 返回内容
	 * @return 处理结果
	 */
	protected ResponseEntity<Object> doFaild(HttpServletRequest request, Object data) {
		return new ResponseEntity<Object>(data,HttpStatus.BAD_REQUEST );
	}

	/**
	 * 异常时返回错误状态码
	 * 
	 * @param request 请求
	 * @param exception 异常信息
	 * @return 处理结果
	 */
	protected ResponseEntity<Object> doFaild(HttpServletRequest request, SysException exception) {
		logger.warn("Request Faild. Path:{} Status:{}", request.getRequestURI(), exception.getStatus());
		return new ResponseEntity<Object>(exception.getStatus());
	}
	
	/**
	 * 用户token
	 * @param request
	 * @return
	 */
	protected int getUserId(HttpServletRequest request) {
		SysUser user= TokenHelper.getLoginUser(request.getHeader("X-Token"));
		return user.getId();
	}
}
